package com.itboye.jinpuyiyuan.activity.home.register;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.bigkoo.pickerview.OptionsPickerView;

import com.itboye.jinpuyiyuan.R;
import com.itboye.jinpuyiyuan.activity.pay.PayActivity;
import com.itboye.jinpuyiyuan.adapter.DateRecylerAdapter;
import com.itboye.jinpuyiyuan.adapter.NewRegisterDoctorDetailAdapter;

import com.itboye.jinpuyiyuan.base.BaseActivity;
import com.itboye.jinpuyiyuan.bean.DateBean;
import com.itboye.jinpuyiyuan.bean.DoctorRegInfoBean;
import com.itboye.jinpuyiyuan.bean.QueryDoctorListBeanNew;

import com.itboye.jinpuyiyuan.bean.preRegistrationBean;
import com.itboye.jinpuyiyuan.presenter.BranchAddressPresenter;
import com.itboye.jinpuyiyuan.utils.dialog.RxDialogDate;
import com.itboye.jinpuyiyuan.utils.sputil.Const;
import com.itboye.jinpuyiyuan.utils.sputil.SPUtils;
import com.itboye.jinpuyiyuan.utils.volley.ResultEntity;
import com.itboye.jinpuyiyuan.widget.loadingutil.MAlert;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.TimeZone;

/**
 * Created by Administrator on 2017/12/9 0009.
 * 挂号详情
 */

public class RegisterDetailActivity extends BaseActivity implements AdapterView.OnItemClickListener, Observer, DateRecylerAdapter.OnItemClickListener {

    //title
    private ImageView leftImg,rightImg;
    private TextView leftTv,tvTitle;
    private RelativeLayout rlLeft,toobar;

    private ListView registerDoctorList;
    private NewRegisterDoctorDetailAdapter registerDoctorDetailAdapter;
    //doctor查询
//    private ArrayList<QueryDoctorListBeanNew.DoctorItem> list=new ArrayList<>();
    private ArrayList<DoctorRegInfoBean> list = new ArrayList<>();

    private RecyclerView recyclerView;
    private DateRecylerAdapter dateRecylerAdapter;
    private ArrayList<DateBean> dateList;//时间bean list
    private RxDialogDate dialogDate;
    private String hid;//分院id
    private String dept_id;//科室id
    private String uid;

    private ArrayList<String> times;// 存储医生列表的挂号时间（1，2）
    private int day; //记录选择的日子（天）
    private ArrayList<String> options;//挂号时间列表
    private ArrayList<String>  hourAndMins=new ArrayList<>();
    private OptionsPickerView pvOptionsUse;

    private BranchAddressPresenter presenter;
    private List<QueryDoctorListBeanNew.DoctorItem> arraylist=new ArrayList<>();



    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_registerdetail);
        leftTv.setVisibility(View.GONE);
        rightImg.setVisibility(View.GONE);
        uid= (String) SPUtils.get(this,null, Const.UID,"");
        tvTitle.setText(getIntent().getStringExtra("title"));
        hid=getIntent().getStringExtra("hid");
        dept_id=getIntent().getStringExtra("dept_id");
        presenter=new BranchAddressPresenter(this);
        initData();

    }

    private void initData() {
        dateList=new ArrayList<>();
        times = new ArrayList<>();
        options=new ArrayList<>();
        getDateList();

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        dateRecylerAdapter=new DateRecylerAdapter(this,dateList);
        recyclerView.setAdapter(dateRecylerAdapter);
        dateRecylerAdapter.setOnItemClickListener(this);

        day=Integer.parseInt(dateList.get(0).getDay());
        registerDoctorDetailAdapter=new NewRegisterDoctorDetailAdapter(this,list);
        registerDoctorList.setAdapter(registerDoctorDetailAdapter);
        presenter.doctorRegInfo(dept_id,"-1",dateList.get(0).getYear()+"-"
                +dateList.get(0).getMonth()+"-"+dateList.get(0).getDay().trim(),
                dateList.get(0).getYear()+"-"
                +dateList.get(0).getMonth()+"-"+dateList.get(0).getDay().trim());
        Log.d("======date","deptid"+dept_id+dateList.get(0).getYear()+"-"
                        +dateList.get(0).getMonth()+"-"+dateList.get(0).getDay());

        registerDoctorList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

//                checkDayTime(times.get(position));//划分时间的flag
                setOptionsList(times.get(position));
                //点击挂号
                initOptionPicker(options);
                pvOptionsUse.show();
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        //item提交按钮点击事件
        view.findViewById(R.id.tvRegister).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


            }
        });
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){

            case R.id.rlLeft:
            case R.id.leftImg:
                this.finish();
                break;
        }
    }

    public void getDateList(){
        Calendar instance = Calendar.getInstance();
        instance.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));

        String year = String.valueOf(instance.get(Calendar.YEAR));
        String month = String.valueOf(instance.get(Calendar.MONTH)+1);
        String day = String.valueOf(instance.get(Calendar.DAY_OF_MONTH));
        String mWay = String.valueOf(instance.get(Calendar.DAY_OF_WEEK));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd");

        int format1 = Integer.valueOf(simpleDateFormat.format(new Date()));
        instance.set(Calendar.DAY_OF_MONTH,instance.getActualMaximum(Calendar.DAY_OF_MONTH));
        Log.d("simpleDate==",simpleDateFormat.format(instance.getTime())+"");
        int format2 = Integer.valueOf(simpleDateFormat.format(instance.getTime()));
        for (int i=format1;i<format2+1;i++){
            instance.set(Calendar.DAY_OF_MONTH,i);
            DateBean dateBean = new DateBean();
            dateBean.setYear(year);
            dateBean.setDay(i+"");
            dateBean.setMonth(month);
            dateBean.setWeek("星期"+getWeekday(String.valueOf(instance.get(Calendar.DAY_OF_WEEK))));
            dateList.add(dateBean);

        }
        instance.set(Calendar.MONTH,instance.get(Calendar.MONTH)+1);
        for (int i=1;i<format1;i++){
            instance.set(Calendar.DAY_OF_MONTH,i);
            DateBean dateBean = new DateBean();
            dateBean.setYear(year);
            dateBean.setDay(i+"");
            dateBean.setMonth(String.valueOf(instance.get(Calendar.MONTH)+1));
            dateBean.setWeek("星期"+getWeekday(String.valueOf(instance.get(Calendar.DAY_OF_WEEK))));
            dateList.add(dateBean);
        }
        //判断跨年时的时间变化

    }

    public String getWeekday(String mWay){

        if("1".equals(mWay)){
            return mWay ="日";
        }else if("2".equals(mWay)){
            return mWay ="一";
        }else if("3".equals(mWay)){
            return mWay ="二";
        }else if("4".equals(mWay)){
            return mWay ="三";
        }else if("5".equals(mWay)){
            return mWay ="四";
        }else if("6".equals(mWay)){
            return mWay ="五";
        }else if("7".equals(mWay)){
            return mWay ="六";
        }
        return "";
    }

    @Override
    public void update(Observable o, Object arg) {
        ResultEntity entity = handlerError(arg);
        if (entity!=null){

//            if (entity.getEventType() == BranchAddressPresenter.By_HospDoct_query_success){
//
//                QueryDoctorListBeanNew doctorlist= (QueryDoctorListBeanNew) entity.getData();
//                list.addAll(doctorlist.getList());
//                registerDoctorDetailAdapter=new NewRegisterDoctorDetailAdapter(this,list);
//                registerDoctorList.setAdapter(registerDoctorDetailAdapter);
//            }else if (entity.getEventType() == BranchAddressPresenter.By_HospDoct_query_fail){
//
//
//            }else

            if (entity.getEventType() == BranchAddressPresenter.By_HospDoct_regInfo_success){
                if (list.size()>0){
                    list.clear();
                }
                if (times.size()>0){
                    times.clear();
                }
                List<DoctorRegInfoBean> doctorList= (List<DoctorRegInfoBean>) entity.getData();
                list.addAll(doctorList);

                for (int i=0;i<doctorList.size();i++){
                    String str="";
                    for (int j=0;j<doctorList.get(i).getReg_list().get(0).getReg_time_list().size();j++){
                        if (j==doctorList.get(i).getReg_list().get(0).getReg_time_list().size()-1){
                            str+=doctorList.get(i).getReg_list().get(0).getReg_time_list().get(j).getTime_flag();
                        }else {
                            str+=doctorList.get(i).getReg_list().get(0).getReg_time_list().get(j).getTime_flag()+",";
                        }
                    }
                    times.add(str);

                }

                registerDoctorDetailAdapter.addData(list);
            }else if (entity.getEventType() == BranchAddressPresenter.By_HospDoct_regInfo_faile){
                MAlert.alert(entity.getMsg());
            }else if (entity.getEventType() == BranchAddressPresenter.By_Order_orderReg_success){ //预挂号

                preRegistrationBean bean= (preRegistrationBean) entity.getData();
                Log.d("order===",bean.toString());
                Intent intent = new Intent(RegisterDetailActivity.this, PayActivity.class);
                intent.putExtra("order_id",bean.getHospOrderId());
                intent.putExtra("remark",bean.getHospRemark());
                startActivity(intent);


            }else if (entity.getEventType() == BranchAddressPresenter.By_Order_orderReg_faile){
                MAlert.alert(entity.getMsg());
            }
        }
    }

   //添加挂号时间列表数据
    private void setOptionsList(String strings) {
        if (options.size()>0){
            options.clear();
        }
        if (strings.contains(",")){
            String[] split = strings.split(",");
            for (int i=0;i<split.length;i++){
                if (split[i].equals("1")){
                 options.add("08:00-11:30");
                }else if (split[i].equals("2")){
                 options.add("13:00-17:00");
                }else if (split[i].equals("3")){
                 options.add("17:00-次日08:00");
                }
            }
        }else {
            if (strings.equals("1")){
                options.add("08:00-11:30");
            }else if (strings.equals("2")){
                options.add("13:00-17:00");
            }else if (strings.equals("3")){
                options.add("17:00-次日08:00");
            }
        }
    }

    // 1	上午 (06:00-12:00)      2	下午 (12:00-18:00)      3	晚上(18:00-次日06:00)
    // 多的用逗号拼接  如 1,2  2,3  1,2,3
    private void checkDayTime(String hour){
      if (hour.equals("1")){
          getHourList(6,12);
      }else if (hour.equals("2")){
          getHourList(12,18);
      }else if (hour.equals("3")){
          getHourList(18,6);
      }else if (hour.equals("1,2")){
          getHourList(6,18);
      }else if (hour.equals("1,3")){
          getHourList(18,12);
      }else if (hour.equals("2,3")){
          getHourList(12,6);
      }else if (hour.equals("1,2,3")){
          getHourList(0,24);
      }

    }
    //获取小时 列表
    private void getHourList(int startHour,int endHour){
        if (hourAndMins.size()>0){
            hourAndMins.clear();
        }
        if (startHour>endHour){
            for (int i=startHour;i<24;i++){
                int d=i+1;
                hourAndMins.add(i+":00-"+d+":00");
            }
            for (int j=0;j<endHour;j++){
                int d=j+1;
                hourAndMins.add(j+":00-"+d+":00");
            }
        }else {
            for (int i=startHour;i<endHour;i++){
                int d=i+1;
                hourAndMins.add(i+":00-"+d+":00");
            }
        }
//        dialogDate=new RxDialogDate(this,startHour,endHour,"选择挂号时间","确定挂号");
//        dialogDate.show();
          initOptionPicker();
          pvOptionsUse.show();
    }

    @Override
    public void onItemClick(View view, int position) {
        dateRecylerAdapter.setSelectId(position);
        //记录item 选择的day
        day=Integer.parseInt(dateList.get(position).getDay());
        //查询排班
        presenter.doctorRegInfo(dept_id,"-1",dateList.get(position).getYear()+"-"
                +dateList.get(position).getMonth()+"-"+dateList.get(position).getDay(),dateList.get(position).getYear()+"-"
                +dateList.get(position).getMonth()+"-"+dateList.get(position).getDay()
        );
    }




    /**
     * 时间选择器
     */
    private void initOptionPicker() {//条件选择器初始化

        /**
         * 注意 ：如果是三级联动的数据(省市区等)，请参照 JsonDataActivity 类里面的写法。
         */
        pvOptionsUse = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置


//                String tx = hourAndMins.get(options1);
//                MAlert.alert(tx);
                //调用预挂号
//                presenter.preRegistration();
            }
        })
                .setTitleText("选择挂号时间")
                .setContentTextSize(16)//设置滚轮文字大小
                .setTitleSize(16)//设置标题文字大小
                .setSubCalSize(16)//设置确定按钮大小
                .setSelectOptions(0, 1)//默认选中项
                .setLineSpacingMultiplier(2.0f)//设置间距倍数,但是只能在1.2-2.0f之间
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setBgColor(Color.WHITE)//滚轮背景颜色
                .setTitleBgColor(Color.WHITE)//标题背景颜色
                .setTitleColor(Color.BLACK)//标题颜色
                .setCancelColor(Color.BLACK)//取消按钮颜色
                .setSubmitColor(Color.BLACK)//确定按钮颜色
                .setTextColorCenter(Color.BLACK)//分割线之间的文字颜色
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setLabels("", "", "")
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();

        pvOptionsUse.setPicker(hourAndMins);//二级选择器
    }

    //有参数的flag
    private void initOptionPicker(final ArrayList<String> strings) {//条件选择器初始化

        /**
         * 注意 ：如果是三级联动的数据(省市区等)，请参照 JsonDataActivity 类里面的写法。
         */
        pvOptionsUse = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
//                String tx = hourAndMins.get(options1);
//                MAlert.alert(strings.get(options1));

                DoctorRegInfoBean.RegTime.ItemRegTime itemRegTime = list.get(0).getReg_list().get(0).getReg_time_list().get(options1);
//                Intent intent = new Intent(RegisterDetailActivity.this, PayActivity.class);
//                startActivity(intent);
                //调用预挂号
                Calendar c = Calendar.getInstance();
                int mHour = c.get(Calendar.HOUR_OF_DAY);//时
                int curDay = c.get(Calendar.DAY_OF_MONTH);// 获取当日期
                int mMin = c.get(Calendar.MINUTE);
//                MAlert.alert(curDay+"日"+mHour+"时"+day+"选择的日子");
//                if (split[i].equals("1")){
//                    options.add("06:00-12:00");
//                }else if (split[i].equals("2")){
//                    options.add("12:00-18:00");
//                }else if (split[i].equals("3")){
//                    options.add("18:00-次日06:00");
//                }
                //判断当天的挂号时间是否选择正确
                if (curDay==day){
                    if (strings.get(options1).equals("08:00-11:30")){
                        if (mHour>=12||(mHour==11&&mMin>30)){
                            MAlert.alert("挂号时间选择有误请重新选择");
                            return;
                        }
                    }else if (strings.get(options1).equals("13:00-17:00")){
                        if (mHour>=17){
                            MAlert.alert("挂号时间选择有误请重新选择");
                            return;
                        }
                    }
                }
                presenter.preRegistration(uid,itemRegTime.getReg_id(),itemRegTime.getReg_level(),dept_id,list.get(0).getDoctor_id(),
                        list.get(0).getReg_list().get(0).getReg_date(),itemRegTime.getTime_flag(),itemRegTime.getReg_fee(),itemRegTime.getTreat_fee() );

            }
        })
                .setTitleText("选择挂号时间")
                .setContentTextSize(16)//设置滚轮文字大小
                .setTitleSize(16)//设置标题文字大小
                .setSubCalSize(16)//设置确定按钮大小
                .setSelectOptions(0, 1)//默认选中项
                .setLineSpacingMultiplier(2.0f)//设置间距倍数,但是只能在1.2-2.0f之间
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setBgColor(Color.WHITE)//滚轮背景颜色
                .setTitleBgColor(Color.WHITE)//标题背景颜色
                .setTitleColor(Color.BLACK)//标题颜色
                .setCancelColor(Color.BLACK)//取消按钮颜色
                .setSubmitColor(Color.BLACK)//确定按钮颜色
                .setTextColorCenter(Color.BLACK)//分割线之间的文字颜色
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setLabels("", "", "")
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();

        pvOptionsUse.setPicker(strings);//二级选择器
    }


}
